package billing.system.db.berkeley;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.je.LockMode;
import com.sleepycat.je.OperationStatus;

public class BDB {
	private static String path = "F:/test/";
	private static final long cacheSize = 1024000L;
	private static Map<String,BDB> dataBaseMap = new HashMap<String, BDB>();
	
	static Environment environment = null;
	private final String encode = "UTF-8";
	static {
		EnvironmentConfig envConfig = new EnvironmentConfig();
		envConfig.setAllowCreate(true);
		envConfig.setCacheSize(cacheSize);
		try {
			File dbFile = new File(path);
			if(!dbFile.exists()){
				dbFile.mkdirs();
			}
			environment = new Environment(dbFile, envConfig);
		} catch (DatabaseException e) {
			e.printStackTrace();
		} 
	}
	
	private Database db ;
	private BDB(Database db) {
		this.db = db;
	}
	public synchronized static BDB getBDB(String dbName) {
		BDB result = null;
		result = dataBaseMap.get(dbName);
		if(null == result ){
			DatabaseConfig dbConfig = new DatabaseConfig();
			dbConfig.setAllowCreate(true);
			try {
				Database value = environment.openDatabase(null, dbName, dbConfig);
				result = new BDB(value);
			} catch (DatabaseException e) {
				e.printStackTrace();
			}
			dataBaseMap.put(dbName, result);
		}
		return result;
	}
	public String get(String key) throws Exception {
		DatabaseEntry queryKey = new DatabaseEntry();
		DatabaseEntry value = new DatabaseEntry();
		queryKey.setData(key.getBytes(encode));
		OperationStatus status = this.db.get(null, queryKey, value, LockMode.DEFAULT);
		if (status == OperationStatus.SUCCESS) {
			return new String(value.getData());
		}
		return null;
	}
	public boolean put(String key, String value){
		byte[] theKey = null;
		byte[] theValue = null;
		try{
			theKey = key.getBytes(encode);
			theValue = value.getBytes(encode);
		}catch (Exception e) {
			e.printStackTrace();
		}
		OperationStatus status = db.put(null, new DatabaseEntry(theKey),
				new DatabaseEntry(theValue));
		if (status == OperationStatus.SUCCESS) {
			return true;
		}
		return false;
	}
	public Database getDataBase() {
		return db;
	}
	
	
}
